<?php
/**
 * --------------------------------------------------------------
 * 导航控制器
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\admin\model\Navigation as NavigationModel;
use app\admin\model\Menu as MenuModel;
use app\admin\model\Column as ColumnModel;
use app\admin\model\Page as PageModel;
use util\Tree;

class Navigation extends AdminBase
{
    /**
     * 导航列表
     */
    public function index()
    {
        $map  = $this->getSimpleSearchMap();
        $list = NavigationModel::where($map['where'])
                ->order('id desc')
                ->paginate(config('app.site_setting.list_rows'), false, [
                    'query' => $map['conditions']
                ]);

        $this->assign([
            'list'         => $list,
            'keyword'      => $map['conditions']['keyword'],
            'search_field' => $map['conditions']['search_field'],
            'title'        => '导航列表'
        ]);
        return $this->fetch();
    }
	
	/**
	 * 新增
	 */
	public function add()
	{
	    if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result   = $this->validate($data, 'Navigation');
            if (true !== $result) $this->error($result);

            if (NavigationModel::create($data)) {
                return $this->success('新增成功', 'index');
            } else {
                return $this->error('新增失败');
            }
		} else {
            $this->assign([
                'title' => '新增导航'
            ]);
		    return $this->fetch();
		}
	}
	
	/**
	 * 编辑
	 */
	public function edit()
	{
		$id = input('id/d');
    	if ($id <= 0 || !is_numeric($id)) $this->error('参数错误');
	    if ($this->request->isPost()) {
            $data = $this->request->post();

            // 验证
            $result   = $this->validate($data, 'Navigation');
            if (true !== $result) $this->error($result);

            if (NavigationModel::update($data)) {
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
		} else {
			$info = NavigationModel::get($id);
			
			$this->assign([
                'info'  => $info,
                'title' => '编辑导航'
            ]);
		    return $this->fetch();
		}
	}
	
	/**
	 * 删除
	 */
	public function delete($ids = 0)
	{
        (int) $ids || $this->error('参数错误');
        $map = ['id' => $ids];

        $result = NavigationModel::where($map)->delete();
		$flag   = MenuModel::where(['nid' => $ids])->delete();
        return $result && $flag ? $this->success('删除成功!') : $this->error('删除失败!');
	}
	
	/**
	 * 禁用/启用
	 * @param array $ids id数组
     * @param integer $status 状态值
     */
    public function setStatus($ids = [], $status)
    {
        empty($ids) && $this->error('请选择要操作的数据');
        !is_numeric((int) $status) && $this->error('参数错误');
        
        $map  = ['id' => $ids];
        $info = NavigationModel::where($map)->setField('status', $status);
        $tips = $status == 1 ? '启用' : '禁用';
        return $info !== FALSE ? $this->success($tips.'成功') : $this->error($tips.'失败');
    }

    /**
     * 导航 - 菜单列表
     * @param integer $nid 导航ID
     */
    public function menuList()
    {
		cookie('__forward__', $_SERVER['REQUEST_URI']);

        $nid = input('nid/d');
    	if ($nid <= 0 || !is_numeric($nid)) $this->error('参数错误');
        
        $navTitle = NavigationModel::where('id', $nid)->value('title');

        $andWhere = ['nid' => $nid];
        $map      = $this->getSimpleSearchMap();

        $map['conditions'] = array_merge($map['conditions'], $andWhere);

        $list = MenuModel::where($map['where'])
                ->where($andWhere)
                ->order('id desc')
                ->paginate(config('app.site_setting.list_rows'), false, [
                    'query' => $map['conditions']
                ]);

        $this->assign([
            'nid'          => $nid,
            'list'         => $list,
            'keyword'      => $map['conditions']['keyword'],
            'search_field' => $map['conditions']['search_field'],
            'title'        => $navTitle . ' - 菜单列表'
        ]);
        return $this->fetch();
    }

    /**
     * 添加菜单
     */
    public function addMenu()
    {
        $nid = input('nid/d');
    	if ($nid <= 0 || !is_numeric($nid)) $this->error('参数错误');

        if ($this->request->isPost()) {
            $data   = $this->request->post();
			
			// 验证
            $result   = $this->validate($data, 'Menu');
            if (true !== $result) $this->error($result);
			
			if (MenuModel::create($data)) {
                cache('nav_menu_list', null);
                return $this->success('新增成功', cookie('__forward__'));
            } else {
                return $this->error('新增失败');
            }
        } else {
            $navTitle = NavigationModel::where('id', $nid)->value('title');

            $smenu = MenuModel::queryOneOrList(['status' => 1], 'id,title,pid', 'list');
            $smenu = Tree::toFormatTree($smenu);
            $smenu = array_merge([0 => ['id' => 0, 'title_show' => '顶级菜单']], $smenu);
            
            $columns = ColumnModel::queryOneOrList(['status' => 1], 'id,title,pid', 'list', 'id asc');
            $columns = $columns ? Tree::toFormatTree($columns) : [];
            $columns = array_merge(array(0 => array('id' => 0, 'title_show' => '请选择栏目')), $columns);
            
            $pages   = PageModel::where(['status' => 1])->field('id,title')->select();
            
            $this->assign([
                'nid'     => $nid,
                'smenu'   => $smenu,
                'columns' => $columns,
                'pages'   => $pages,
                'title'   => $navTitle . ' - 添加菜单',
            ]);
            return $this->fetch();
        }
    }
    
    /**
     * 编辑菜单
     */
    public function editMenu()
    {
        
        $id = input('id/d');
    	if ($id <= 0 || !is_numeric($id)) $this->error('参数错误');

        if ($this->request->isPost()) {
            $data   = $this->request->post();
			
			// 验证
            $result   = $this->validate($data, 'Menu');
            if (true !== $result) $this->error($result);
			
			if (MenuModel::update($data)) {
                cache('nav_menu_list', null);
                return $this->success('编辑成功', cookie('__forward__'));
            } else {
                return $this->error('编辑失败');
            }
        } else {
            $info  = MenuModel::get($id);

            $navTitle = NavigationModel::where('id', $info['nid'])->value('title');

            $smenu = MenuModel::queryOneOrList(['status' => 1], 'id,title,pid', 'list');
            $smenu = Tree::toFormatTree($smenu);
            $smenu = array_merge([0 => ['id' => 0, 'title_show' => '顶级菜单']], $smenu);
            
            $columns = ColumnModel::queryOneOrList(['status' => 1], 'id,title,pid', 'list', 'id asc');
            $columns = $columns ? Tree::toFormatTree($columns) : [];
            $columns = array_merge(array(0 => array('id' => 0, 'title_show' => '请选择栏目')), $columns);
            
            $pages   = PageModel::where(['status' => 1])->field('id,title')->select();
            
            $this->assign([
                'info'    => $info,
                'smenu'   => $smenu,
                'columns' => $columns,
                'pages'   => $pages,
                'title'   => $navTitle . ' - 编辑菜单',
            ]);
            return $this->fetch();
        }
    }
	
	/**
	 * 删除
	 */
	public function deleteMenu($ids = 0)
	{
        (int) $ids || $this->error('参数错误');
        $map  = ['id' => $ids];

		$flag = MenuModel::where(['id' => $ids])->delete();
        if ($flag) {
            cache('nav_menu_list', null);
            return $this->success('删除成功!');
        } else {
            return $this->error('删除失败!');
        }
	}
	
	/**
	 * 禁用/启用
	 * @param array $ids id数组
     * @param integer $status 状态值
     */
    public function setMenuStatus($ids = [], $status)
    {
        empty($ids) && $this->error('请选择要操作的数据');
        !is_numeric((int) $status) && $this->error('参数错误');
        
        $map  = ['id' => $ids];
        $info = MenuModel::where($map)->setField('status', $status);
        $tips = $status == 1 ? '启用' : '禁用';
        if ($info !== false) {
            cache('nav_menu_list', null);
            return $this->success($tips.'成功');
        } else {
            return $this->error($tips.'失败');
        }
    }
}